package cn.phub.pet.service.impl;

import cn.phub.basic.service.impl.BaseServiceImpl;
import cn.phub.pet.domain.PetType;
import cn.phub.pet.mapper.PetTypeMapper;
import cn.phub.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jijie
 * @since 2022-04-10
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> queryTree() {
        //一次性查询出所有数据，放到内存 all
        List<PetType> allPetType = petTypeMapper.loadAll();
        //将数据转换成map <Long,PetType>
        HashMap<Long, PetType> allsMap = new HashMap<>();
        for (PetType department : allPetType) {
            allsMap.put(department.getId(), department);
        }
        //从所有数据中找出第一层级 first   我们需要返回的数据
        List<PetType> firstPetTypes = new ArrayList<>();
        for (PetType temp : allPetType) {
            if(temp.getPid() == null){//封装第一层级
                firstPetTypes.add(temp);
            }else{
                //只要不是第一层级的，找自己的上级，并将自己放入上级的children中
                PetType parent = allsMap.get(temp.getPid());
                if(parent != null){
                    parent.getChildren().add(temp);
                }
            }
        }
        return firstPetTypes;
    }
}
